package com.czk.rocketmq.transcation;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * 发送异步消息
 * 拥有回调函数，线程不会停止
 * @Author:ChenZhangKun
 * @Date: 2020/9/3 21:34
 */
@SuppressWarnings("all")
public class Producer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        // 1.创建消息生产者producer，并制定生产者组名
        TransactionMQProducer producer=new TransactionMQProducer("group1");
        // 2.指定Nameserver地址
        producer.setNamesrvAddr("192.168.25.133:9876;192.168.25.134:9876");
        String[] tag={"tag1","tag2","tag3"};
        // 设置事务监听器
        producer.setTransactionListener(new TransactionListener() {
            /**
             * 执行本地事务处理
             * @param message
             * @param o
             * @return
             */
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                if (StringUtils.equals("tag1",message.getTags())){
                    // 提交
                    return LocalTransactionState.COMMIT_MESSAGE;
                }else if (StringUtils.equals("tag2",message.getTags())){
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }else if (StringUtils.equals("tag3",message.getTags())){
                    return LocalTransactionState.UNKNOW;
                }
                return LocalTransactionState.UNKNOW;
            }

            /**
             * 对事务状态的回查->unknow型的
             * @param messageExt
             * @return
             */
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                System.out.println("消息的tag "+messageExt.getTags());
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });
        // 3.启动producer
        producer.start();
        // 4.创建消息对象，指定主题Topic、Tag和消息体
        for (int i = 0; i < 3; i++) {
            // 消息主题
            // 消息tag
            // 消息内容
            Message message=new Message("transaction",tag[i],("hello world "+i).getBytes());
            // 5.发送消息
            // 不针对某一挑进行消息控制，全部进行
           producer.sendMessageInTransaction(message,null);

            TimeUnit.SECONDS.sleep(1);
        }
      //  producer.shutdown();
    }
}
